/** 有问题,弃用 -> 会导致输入框的值无法清空 */

const limitReg = /[\|&;\$<>\(\)\+\/{}\[\]【】\*\^\?]+/g
let currentInput = null
export default {
  bind(el, binding) {
    // 获取当前帮i的那个节点信息
    getInputElement(el)
    if(!currentInput){
      console.error('当前节点下不存在可绑定该指令的节点')
      return
    }
    limitInput(currentInput,binding)
    currentInput.onblur = function () {
      limitInput(currentInput,binding)
    }
    currentInput.onchange = function () {
      limitInput(currentInput,binding)
    }
  },
  update(el, binding) {
    getInputElement(el)
    limitInput(currentInput,binding)
  },
  unbind(el, binding) {
    getInputElement(el)
    currentInput.onblur = null
    currentInput.onchange = null
    currentInput.oninput = null
  }
}

// 限制输入
function limitInput(el,binding) {
  var inputEvent = document.createEvent('HTMLevents')
  inputEvent.initEvent('input',false,false)
  el.value = el.value.replace(limitReg,'')
  binding.value = el.value
  el.dispatchEvent(inputEvent)
}

// 获取input / textarea节点
function getInputElement(el) {
  if(el.tagName.toLowerCase() == 'input' || el.tagName.toLowerCase() == 'textarea') currentInput = el
  if(el.children.length > 0){
    let mark = 0
    for(let i = 0;i < el.children.length;i++){
      if(el.children[i].tagName.toLowerCase() == 'input' || el.children[i].tagName.toLowerCase() == 'textarea'){
        mark++
        currentInput = el.children[i]
        break
      }
    }
    if(mark == 0){
      for(let i = 0;i < el.children.length;i++){
        getInputElement(el.children[i])
      }
    }
  } else {
    currentInput = null
  }
}
